package com.example.state.machine.config;

import com.example.state.machine.enums.TicketEvent;
import com.example.state.machine.enums.TicketState;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/*
 * 工单状态机配置
 */
@Configuration
@EnableStateMachineFactory
public class TicketStateMachineConfig extends EnumStateMachineConfigurerAdapter<TicketState, TicketEvent> {

    @Override
    public void configure(StateMachineStateConfigurer<TicketState, TicketEvent> states) throws Exception {
        states
                .withStates()
                .initial(TicketState.CREATED)
                .states(EnumSet.allOf(TicketState.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<TicketState, TicketEvent> transitions) throws Exception {
        transitions
                // 开始处理：CREATED → PROCESSING
                .withExternal()
                .source(TicketState.CREATED).target(TicketState.PROCESSING)
                .event(TicketEvent.START_PROCESS)
                .and()

                // 解决：PROCESSING → RESOLVED
                .withExternal()
                .source(TicketState.PROCESSING).target(TicketState.RESOLVED)
                .event(TicketEvent.RESOLVE)
                .and()

                // 重新打开：RESOLVED → PROCESSING
                .withExternal()
                .source(TicketState.RESOLVED).target(TicketState.PROCESSING)
                .event(TicketEvent.REOPEN)
                .and()

                // 关闭：RESOLVED → CLOSED
                .withExternal()
                .source(TicketState.RESOLVED).target(TicketState.CLOSED)
                .event(TicketEvent.CLOSE);
    }
}